package com.clementheliou.cheliou.dal.dao.mark.impl;

import java.util.List;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.clementheliou.cheliou.dal.dao.generic.GenericDAO;
import com.clementheliou.cheliou.dal.dao.generic.impl.GenericHibernateDAO;
import com.clementheliou.cheliou.dal.dao.mark.MarkDAO;
import com.clementheliou.cheliou.dal.model.mark.Mark;

/**
 * Hibernate-based implementation of the DAO dedicated to the {@link Mark}
 * entities.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link GenericHibernateDAO};
 * @see {@link GenericDAO};
 * @see {@link Mark};
 * @see {@link Repository}.
 * @since 1.0
 */
@Repository
public class MarkHibernateDAO extends GenericHibernateDAO<Mark> implements MarkDAO {

	/**
	 * Logger for this class.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link Logger};
	 * @see {@link LoggerFactory}.
	 * @since 1.0
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(MarkHibernateDAO.class);

	/**
	 * <i>{@inheritDoc} </i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public Mark getMarkOfMember(Integer photoId, Integer memberId) {
		LOGGER.debug("Get the mark of the member {} for the photo {}.", memberId, photoId);

		final StringBuilder queryBuilder = new StringBuilder("FROM ").append(Mark.class.getName()).append(" as mark ");
		queryBuilder.append("WHERE mark.markedPhoto.id = :photoId ");
		queryBuilder.append("AND mark.author.id = :memberId ");

		final Query query = getCurrentSession().createQuery(queryBuilder.toString());
		query.setParameter("memberId", memberId);
		query.setParameter("photoId", photoId);

		return (Mark) query.uniqueResult();
	}

	/**
	 * <i>{@inheritDoc}</i>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Integer> getMarksOfPhoto(Integer photoId) {
		LOGGER.debug("Get the marks for the photo {}.", photoId);

		final StringBuilder queryBuilder = new StringBuilder("SELECT mark.rank ");
		queryBuilder.append("FROM ").append(Mark.class.getName()).append(" as mark ");
		queryBuilder.append("WHERE mark.markedPhoto.id = :photoId ");

		final Query query = getCurrentSession().createQuery(queryBuilder.toString());
		query.setParameter("photoId", photoId);

		return (List<Integer>) query.list();
	}

}
